package 数据结构.search;

/**
 * 差值查找算法
 */
public class InsertValueSearch {
    public static void main(String[] args) {
        int[] arr = new int[100];
        for (int i = 0; i < 100; i++) {
            arr[i] = i + 1;
        }


        int i = insertValueSearch(arr, 0, arr.length - 1, 100);
        System.out.println(i);

    }

    public static int insertValueSearch(int[] arr, int left, int right, int findVal) {
        //限制条件必须得有
        if (left > right || findVal < arr[0] || arr[arr.length - 1] < findVal) {
            return -1;
        }
        int midNum = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
        int mid = arr[midNum];

        if (findVal > mid) {//向右侧递归查找
            return insertValueSearch(arr, midNum + 1, right, findVal);
        } else if (findVal < mid) {
            return insertValueSearch(arr, left, midNum - 1, findVal);
        } else {
            return midNum;
        }
    }
}
